<template>
  <div class="part-emission-distribution-chart-container" ref="pieChartRef"></div>
</template>

<script lang="ts" setup name="PartEmissionDistributionChart">
import { ref, defineProps, defineExpose } from 'vue';
import { useECharts } from '@/hooks/useECharts';
import type { GetModelPartsEmissionResult } from '@/apis/pcf/pcfForm/model/pcfFormModel';
import Decimal from 'decimal.js';
import { tofixed } from '@/utils';
interface PartEmissionDistributionChartProps {
  emissionData: GetModelPartsEmissionResult;
}
const props = defineProps<PartEmissionDistributionChartProps>();

const pieChartRef = ref();
const { setOptions } = useECharts(pieChartRef);

function init() {
  const itemEmissionInfo = props.emissionData.itemEmissionInfo || [];
  const itemEmissionProportionInfo = props.emissionData.itemEmissionProportionInfo || [];
  const xAxisData: string[] = [];
  const emissionYAxisData: {
    value: number | string;
    rate: number;
    originalValue: number | string;
  }[] = [];
  const proportionYAxisData: number[] = [];
  // 最大排放
  let maxEmission = 0;
  for (let i = 0; i < itemEmissionInfo.length; i++) {
    const item = itemEmissionInfo[i];
    const pItem = itemEmissionProportionInfo[i];
    xAxisData.push(item.itemName);
    emissionYAxisData.push({
      value: parseFloat((item.emission || 0).toFixed(3)),
      originalValue: item.emission,
      rate: Number(tofixed(Decimal.mul(pItem.proportion || 0, 100).toNumber(), 2))
    });
    maxEmission = Math.max(maxEmission, item.emission);
    proportionYAxisData.push(Decimal.mul(pItem.proportion || 0, 100).toNumber());
  }

  const { maxEmission: maxValue, emissionInterval } = getEmissionInterval(maxEmission, 5);

  const dataZoom = [
    {
      type: 'slider', // 缩放滑动条
      xAxisIndex: 0, // 对第一个横轴进行缩放
      start: 0, // 缩放起始位置（百分比）
      maxValueSpan: 20,
      height: 10,
      bottom: 20,
      brushSelect: true
    }
  ];
  let option: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params: any) {
        const params1 = params[0];
        const params2 = params[1];

        const { name, color, data, marker } = params1 || {};
        let str = `<span style='font-weight: 600;'>${name}</span>` + '<br/>';

        str +=
          marker +
          `<span>碳排量：${data.value} kg CO₂e</span><br />` +
          params2.marker +
          `<span>累计排放占比：${data.rate}%</span>`;
        return str;
      }
    },
    // dataZoom: [
    //   {
    //     type: 'slider', // 缩放滑动条
    //     xAxisIndex: 0, // 对第一个横轴进行缩放
    //     start: 0, // 缩放起始位置（百分比）
    //     end: 100, // 缩放结束位置（百分比）
    //     height: 10
    //   }
    // ],
    legend: {
      data: ['碳排量', '累计排放占比'],
      x: 'center',
      bottom: '15',
      textStyle: {
        lineHeight: 56
      }
    },
    grid: {
      top: '20',
      left: 20,
      right: 20,
      bottom: '80',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisTick: {
        show: false // 隐藏 X 轴的分割点
      },
      axisLine: {
        lineStyle: {
          color: '#E1E6EB' // 设置横轴的颜色为红色
        }
      },
      axisLabel: {
        color: '#7A8A99',
        interval: 0, // 这使得所有的标签都会显示
        formatter: function (value: string) {
          return value.length > 5 ? value.slice(0, 5) + '...' : value;
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        min: 0,
        max: maxValue,
        interval: emissionInterval
      },
      {
        type: 'value',
        min: 0,
        max: 100,
        interval: 20,
        axisLabel: {
          formatter: function (value: string) {
            return value + '%'; // 将纵轴 label 的值添加百分号
          }
        }
      }
    ],

    series: [
      {
        name: '碳排量',
        data: emissionYAxisData,
        type: 'bar',
        barWidth: 28,
        itemStyle: {
          color: 'rgba(3, 172, 130, 0.8)'
        }
      },
      {
        name: '累计排放占比',
        data: proportionYAxisData,
        yAxisIndex: 1,
        type: 'line',
        itemStyle: {
          color: 'rgba(48, 139, 242, 1)'
        }
      }
    ]
  };
  if (xAxisData.length > 20) {
    Object.assign(option, { dataZoom });
  }
  return option;
}

function getEmissionInterval(maxValue: number, interval = 5) {
  const intNumString = maxValue.toFixed(0);
  let maxlength = intNumString.length;
  const mul = Math.pow(10, maxlength - 1);
  const max = (Number(intNumString[0]) + 1) * mul;
  return {
    maxEmission: max,
    emissionInterval: max / interval
  };
}

function renderChart() {
  const option = init();
  setOptions(option);
}

defineExpose({
  renderChart
});
</script>

<style lang="scss" scoped>
.part-emission-distribution-chart-container {
  width: 100%;
  height: 342px;
}
</style>
